<template>
  <div class="horizontal-project-form">
    <div class="page-header">
      <h2>{{ isEdit ? '编辑横向课题' : '添加横向课题' }}</h2>
      <div>
        <el-button @click="$router.go(-1)">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          <el-icon><Check /></el-icon>
          {{ isEdit ? '更新' : '保存' }}
        </el-button>
      </div>
    </div>

    <el-card>
      <el-form 
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        size="default"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="项目名称" prop="projectName">
              <el-input 
                v-model="form.projectName" 
                placeholder="请输入项目名称"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同号" prop="contractNumber">
              <el-input 
                v-model="form.contractNumber" 
                placeholder="请输入合同号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同总金额(万元)" prop="contractAmount">
              <el-input-number 
                v-model="form.contractAmount" 
                :min="0"
                :precision="2"
                style="width: 100%"
                placeholder="请输入合同总金额"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="甲方单位名称" prop="partyAName">
              <el-input 
                v-model="form.partyAName" 
                placeholder="请输入甲方单位名称"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目负责人" prop="projectLeader">
              <el-input 
                v-model="form.projectLeader" 
                placeholder="请输入项目负责人"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行负责人" prop="executionLeader">
              <el-input 
                v-model="form.executionLeader" 
                placeholder="请输入执行负责人"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="期限" prop="duration">
              <el-input 
                v-model="form.duration" 
                placeholder="请输入项目期限"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="参与人" prop="participants">
              <el-input 
                v-model="form.participants" 
                type="textarea"
                :rows="3"
                placeholder="请输入参与人员，多人用逗号分隔"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="财务账号" prop="financialAccount">
              <el-input 
                v-model="form.financialAccount" 
                placeholder="请输入财务账号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结题时间" prop="completionTime">
              <el-date-picker
                v-model="form.completionTime"
                type="date"
                placeholder="请选择结题时间"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="到款记录" prop="fundingRecord">
              <el-input 
                v-model="form.fundingRecord" 
                type="textarea"
                :rows="3"
                placeholder="请输入到款记录"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="到款凭证" prop="fundingVoucher">
              <el-input 
                v-model="form.fundingVoucher" 
                type="textarea"
                :rows="2"
                placeholder="请输入到款凭证信息"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="结题证明" prop="completionCertificate">
              <el-input 
                v-model="form.completionCertificate" 
                placeholder="请输入结题证明"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结题报告" prop="completionReport">
              <el-input 
                v-model="form.completionReport" 
                placeholder="请输入结题报告"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Check } from '@element-plus/icons-vue'
import { projectAPI } from '@/api/project'

export default {
  name: 'HorizontalProjectForm',
  components: {
    ArrowLeft,
    Check
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    
    const formRef = ref()
    const submitting = ref(false)
    const isEdit = computed(() => !!route.params.id)
    
    const form = reactive({
      projectName: '',
      contractNumber: '',
      contractAmount: null,
      partyAName: '',
      projectLeader: '',
      executionLeader: '',
      duration: '',
      participants: '',
      financialAccount: '',
      completionTime: '',
      fundingRecord: '',
      fundingVoucher: '',
      completionCertificate: '',
      completionReport: ''
    })
    
    const rules = reactive({
      projectName: [
        { required: true, message: '请输入项目名称', trigger: 'blur' }
      ],
      contractNumber: [
        { required: true, message: '请输入合同号', trigger: 'blur' }
      ],
      contractAmount: [
        { required: true, message: '请输入合同总金额', trigger: 'blur' }
      ],
      partyAName: [
        { required: true, message: '请输入甲方单位名称', trigger: 'blur' }
      ],
      projectLeader: [
        { required: true, message: '请输入项目负责人', trigger: 'blur' }
      ],
      executionLeader: [
        { required: true, message: '请输入执行负责人', trigger: 'blur' }
      ]
    })
    
    const loadProjectData = async () => {
      if (!isEdit.value) return
      
      try {
        const response = await projectAPI.getHorizontalProject(route.params.id)
        const project = response.data
        
        Object.keys(form).forEach(key => {
          if (project[key] !== undefined) {
            form[key] = project[key]
          }
        })
      } catch (error) {
        console.error('加载课题数据失败:', error)
        ElMessage.error('加载课题数据失败')
        router.go(-1)
      }
    }
    
    const handleSubmit = async () => {
      try {
        await formRef.value.validate()
        
        submitting.value = true
        
        if (isEdit.value) {
          await projectAPI.updateHorizontalProject(route.params.id, form)
          ElMessage.success('更新成功')
        } else {
          await projectAPI.createHorizontalProject(form)
          ElMessage.success('创建成功')
        }
        
        router.push('/horizontal-projects/list')
      } catch (error) {
        if (error.message) {
          console.error('提交失败:', error)
          ElMessage.error(error.message || '提交失败')
        }
      } finally {
        submitting.value = false
      }
    }
    
    onMounted(() => {
      loadProjectData()
    })
    
    return {
      formRef,
      form,
      rules,
      submitting,
      isEdit,
      handleSubmit
    }
  }
}
</script>

<style lang="scss" scoped>
.horizontal-project-form {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: #303133;
    }
  }
  
  .el-form {
    .el-form-item {
      margin-bottom: 22px;
    }
  }
}
</style>
